import { Component, OnInit, Injector, ViewChild, Output, EventEmitter } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import {
    CodeRuleEditDto,
    CodeItemServiceProxy,
    Base_DataItemDetailServiceProxy,
    ComboboxItemDto
} from '@shared/service-proxies/stock-service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import { finalize } from 'rxjs/operators';
@Component({
    selector: 'createOrEditCodeRuleModal',
    templateUrl: './create-or-edit-coderule-modal.component.html'
})
export class CreateOrEditCodeRuleModalComponent extends AppComponentBase implements OnInit {
    constructor(
        injector: Injector,
        private _coderuleServiceProxy: CodeItemServiceProxy,
        private _dataItemDetailService: Base_DataItemDetailServiceProxy
    ) {
        super(injector);
    }
    @ViewChild('createOrEditModal') modal: ModalDirective;
    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;
    coderule_id: string;
    value: string;
    coderule: CodeRuleEditDto = new CodeRuleEditDto();
    deptitems: ComboboxItemDto[];
    typename: string;
    ngOnInit(): void {
        this._dataItemDetailService.getComboxDataitems('ruleType').subscribe(result => {
            this.deptitems = result;
        });
    }

    show(): void {
        const self = this;
        self.active = true;
        self.coderule_id = '';
        self.coderule = new CodeRuleEditDto();
        self.modal.show();
    }

    showupdate(event): void {
        const self = this;
        self.active = true;
        self.coderule_id = event.id;
        self.coderule = event;

        self.modal.show();
    }
    getTypeName(event): void {
        this.coderule.f_TypeName = this.deptitems.find(e => e.value == event.target.value).displayText;
    }
    onShown(): void {
        //   document.getElementById('f_ProductName').focus();
    }

    save(): void {
        this.saving = true;
        this._coderuleServiceProxy
            .createOrUpdateCodeRuleAsync(this.coderule)
            .pipe(
                finalize(() => {
                    this.saving = false;
                })
            )
            .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(null);
            });
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }
}
